﻿//------------------------------------------------------------------------------
// <copyright company="Tunynet">
//     Copyright (c) Tunynet Inc.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using Tunynet.Events;
using Tunynet.Logging;

namespace Tunynet.Common
{
    /// <summary>
    /// 勋章创建和删除的事件
    /// </summary>
    public class PointTaskEventModule : IEventMoudle
    {
        private MedalService medalService;
        private AttachmentService attachmentService = new AttachmentService(TenantTypeIds.Instance().Medal());
        private IKvStore kvStore;
        private RoleService roleService;
        private OperationLogService operationLogService;
        private NoticeService noticeService;
        private INoticeSender noticeSender;
        private PointService pointService;
        private PointTaskService pointTaskService;

        //构造
        public PointTaskEventModule(MedalService medalService, IKvStore kvStore, RoleService roleService, OperationLogService operationLogService, NoticeService noticeService, INoticeSender noticeSender, PointService pointService, PointTaskService pointTaskService)
        {
            this.medalService = medalService;
            this.kvStore = kvStore;
            this.roleService = roleService;
            this.operationLogService = operationLogService;
            this.noticeService = noticeService;
            this.noticeSender = noticeSender;
            this.pointService = pointService;
            this.pointTaskService = pointTaskService;
        }

        /// <summary>
        /// 注册事件处理程序
        /// </summary>
        public void RegisterEventHandler()
        {
            EventBus<PointTask>.Instance().After += new CommonEventHandler<PointTask, CommonEventArgs>(PointTaskOperation_After);
            EventBus<PointTaskRecord>.Instance().After += new CommonEventHandler<PointTaskRecord, CommonEventArgs>(TaskToUserOperation_After);
        }

        /// <summary>
        /// 积分任务事件
        /// </summary>
        /// <param name="comment"></param>
        /// <param name="eventArgs"></param>
        private void PointTaskOperation_After(PointTask pointTask, CommonEventArgs eventArgs)
        {
            //日志
            OperationLog newLog = new OperationLog(eventArgs.OperatorInfo);
            newLog.OperationObjectId = pointTask.TaskId;
            newLog.OperationObjectName = pointTask.TaskName;
            newLog.OperationType = eventArgs.EventOperationType;
            newLog.OperationUserRole = string.Join(",", roleService.GetRoleNamesOfUser(eventArgs.OperatorInfo.OperationUserId));
            if (eventArgs.EventOperationType == EventOperationType.Instance().Create())
            {
                newLog.Description = $"{eventArgs.OperatorInfo.Operator}添加积分任务:{pointTask.TaskName}";
            }
            else if (eventArgs.EventOperationType == EventOperationType.Instance().Update())
            {
                newLog.Description = $"{eventArgs.OperatorInfo.Operator}更新积分任务:{pointTask.TaskName}";
            }
            else if (eventArgs.EventOperationType == EventOperationType.Instance().Delete())
            {
                newLog.Description = $"{eventArgs.OperatorInfo.Operator}删除积分任务:{pointTask.TaskName}";
                //删除用户积分任务领取记录
                pointTaskService.DeleteTasktoUserByTaskId(pointTask.TaskId);
            }
            //写入日志
            operationLogService.Create(newLog);
        }

        /// <summary>
        /// 任务记录事件
        /// </summary>
        /// <param name="comment"></param>
        /// <param name="eventArgs"></param>
        private void TaskToUserOperation_After(PointTaskRecord record, CommonEventArgs eventArgs)
        {
            var task = pointTaskService.Get(record.TaskId);
            if (eventArgs.EventOperationType == EventOperationType.Instance().Create())
            {
                //计数+1
                kvStore.Increase(KvKeys.Instance().PointTasktoUser(record.TaskId));
            }
            else if (eventArgs.EventOperationType == EventOperationType.Instance().Update())
            {
                if (record.Status == TaskRecordStatus.Abandoned)
                {
                    //计数-1
                    kvStore.Increase(KvKeys.Instance().PointTasktoUser(record.TaskId), -1);
                }
                else if (record.Status == TaskRecordStatus.Completed)
                {
                    //加积分和金币
                    pointService.Reward(record.UserId, eventArgs.OperatorInfo.OperationUserId, task.AwardPoints, 0, task.AwardGolds, "完成积分任务：" + task.TaskName + ",奖励" + task.AwardPoints + "经验+" + task.AwardGolds + "金币");

                    if (string.IsNullOrEmpty(task.TaskType.CheckMethodName) && eventArgs.OperatorInfo.OperationUserId != record.UserId)
                    {
                        //发送通知(积分任务审核通过)
                        Notice notice = Notice.New();
                        notice.ReceiverId = record.UserId;
                        notice.RelativeObjectName = task.TaskName;
                        notice.NoticeTypeKey = NoticeTypeKeys.Instance().TaskApproved();
                        notice.RelativeObjectUrl = CachedUrlHelper.Action("PointTask", "UserSpace");
                        notice.LeadingActor = record.UserDisplayName;
                        notice.LeadingActorUserId = record.UserId;
                        notice.LeadingActorUrl = SiteUrls.Instance().SpaceHome(record.UserId);
                        noticeService.Create(notice);
                        noticeSender.Send(notice);
                    }
                }
                else if (record.Status == TaskRecordStatus.Refused && eventArgs.OperatorInfo.OperationUserId != record.UserId)
                {
                    //发送通知(积分任务审核不通过)
                    Notice notice = Notice.New();
                    notice.ReceiverId = record.UserId;
                    notice.RelativeObjectName = task.TaskName;
                    notice.Body = record.Feedback.Replace("<br />","");
                    notice.NoticeTypeKey = NoticeTypeKeys.Instance().TaskDisapproved();
                    notice.RelativeObjectUrl = CachedUrlHelper.Action("PointTask", "UserSpace");
                    notice.LeadingActor = record.UserDisplayName;
                    notice.LeadingActorUserId = record.UserId;
                    notice.LeadingActorUrl = SiteUrls.Instance().SpaceHome(record.UserId);
                    noticeService.Create(notice);
                    noticeSender.Send(notice);
                }
            }
            else if (eventArgs.EventOperationType == EventOperationType.Instance().Delete())
            {
            }
        }
    }
}